package com.example.tys.baseapplication.NetModel.okhttp.requset;

import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;


import com.example.tys.baseapplication.NetModel.okhttp.OkHttpClientManger;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.net.URLConnection;
import java.net.URLDecoder;

import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * Created by Administrator on 2016/10/27.
 * 单个文件post
 */
public class PostFileRequestBuilder extends BaseRequest<PostFileRequestBuilder> {

    private static final String TAG = "PostFileRequestBuilder";
    private File file;

    @Override
    public Call build() {
        Request req = new Request.Builder()
                .post(addFileBody(file))
                .url(url)
                .headers(addHead(heads))
                .tag(tag)
                .build();
        return OkHttpClientManger.getClient("").newCall(req);
    }

    private RequestBody addFileBody(@NonNull File file) {
        return RequestBody.create(MediaType.parse(getMiMeType(file.getName())), file);

    }

    private String getMiMeType(@NonNull String fileName) {
        String mimeType = null;
        try {
            mimeType = URLConnection.getFileNameMap().getContentTypeFor(URLDecoder.decode(fileName, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        if (TextUtils.isEmpty(mimeType)) {
            mimeType = "application/octet-stream";
        }
        return mimeType;
    }

    /**
     * @param filePath
     * @param <T>
     * @return
     * @throws FileNotFoundException
     */
    public <T extends BaseRequest> T file(String filePath) throws FileNotFoundException {
        File file = new File(filePath);
        if (file.exists() && file.isFile()) {
            this.file = file;
        } else {
            Log.e(TAG, "file of posted is not found(" + filePath + ")");
            throw new FileNotFoundException("file of posted is not found");
        }
        return (T) this;
    }


}
